﻿using SAM.Framework.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SAM.Configuration.Domain
{
    /// <summary>
    /// 配置文件管理聚合根
    /// 需要继承实现很多的接口，以及一些逻辑的处理
    /// </summary>
    public class ConfigurationAggregateRoot:IRead, IWriter
    { 
        
        Dictionary<FileType, Domain.AbstractConfigurationBuild> builds = new Dictionary<FileType, Domain.AbstractConfigurationBuild>();

        public ConfigurationAggregateRoot()
        {
            builds.Add(FileType.JSON, new Domain.JSONConfigurationBuild());
            builds.Add(FileType.XML, new Domain.XMLConfigurationBuild());
            this.DefaultFileName = "Default";
        }

        public ConfigurationAggregateRoot(string baseFilePath)
        {
            builds.Add(FileType.JSON, new Domain.JSONConfigurationBuild(baseFilePath));
            builds.Add(FileType.XML, new Domain.XMLConfigurationBuild(baseFilePath));
            this.DefaultFileName = "Default";
        }

        #region property

        /// <summary>
        /// 默认配置文件名，不带扩展名
        /// </summary>
        public string DefaultFileName
        {
            get;
            set;
        }

        #endregion


        public T Read<T>(FileType fileType)
        {
            string fileName = string.Format("{0}.{1}", this.DefaultFileName, fileType.ToString());
            return this.Read<T>(fileName, fileType);
        }

        public T Read<T>(string fileName, FileType fileType)
        {
            return builds[fileType].Read<T>(fileName);
        }

        public void Writer<T>(FileType fileType, T data)
        {
            string fileName = string.Format("{0}.{1}", this.DefaultFileName, fileType.ToString());
            this.Writer<T>(fileName, fileType, data);
        }

        public void Writer<T>(string fileName, FileType fileType, T data)
        {
            builds[fileType].Write<T>(fileName, data);
        }
    }
}
